#!/bin/bash

dir_name=$(dirname $0)

start(){
  nohup python3 ${dir_name}/serve.py > mock.log 2>&1 &
  echo $! > run.pid
  cat run.pid
  echo "start ......"
  sleep 3
  tail -f 100 ${dir_name}/mock.log
}

stop(){
  pid_file=${dir_name}/run.pid

  if [ -f ${pid_file} ];then
      run_pid=`cat ${pid_file}`
      if [ -z ${run_pid} ];then
          pid=`ps -ef|grep "${dir_name}"|awk '{print $2}'`
          [ -z ${pid} ] || kill -9 ${pid}
          # echo "Not found pid!, please check it manual, ps -ef| grep 'python3 server'"
      else
          kill ${run_pid} && cat /dev/null > run.pid
          echo "already stop ${dir_name}/serve.py pid: ${run_pid} ......"
      fi
  else
       pid=`ps -ef|grep 'python3 serve.py'|awk '{print $2}'`
       [ -z ${pid} ] || kill -9 ${pid}
       # echo "Not found run.pid!!!"
  fi
}

restart(){
  stop
  start
}


case $1 in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "restart")
    restart
    ;;
  "*")
    echo "please use >>./run.sh start | stop | restart"
    ;;
esac